package com.mini.controller;

import com.mini.bean.WxUser;
import com.mini.utils.ResultDTO;
import com.mini.service.WxService;
import com.mini.utils.LoginUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.text.SimpleDateFormat;
import java.util.*;

//扫码租借模块
@RestController
@RequestMapping("/webchat")
public class WxUserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private WxService wxService;



    /**
     * 登陆接口
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET,produces= "application/json;charset=utf-8" )
    public ResultDTO login(String encryptedData, String iv, String code) {
        Map map = new HashMap<>();
        WxUser user = new WxUser();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        String date = df.format(new Date());
        String session_key = null;
        JSONObject userInfo = null;
        String token = LoginUtil.getWebAccess(code);
        String rec = LoginUtil.httpGet(token);
        JSONObject json = JSON.parseObject(rec);
        if (json != null) {
            session_key = json.getString("session_key");
        }

        byte[] dataByte = Base64.decode(encryptedData);// 被加密的数据
        byte[] keyByte = Base64.decode(session_key);// 加密秘钥
        byte[] ivByte = Base64.decode(iv);// 偏移量
        try {

            int base = 16;
            if (keyByte.length % base != 0) {// 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                userInfo = JSON.parseObject(result);
            }
            logger.info("User information:"+userInfo);

            user.setWxopenid(userInfo.getString("openId"));
            user.setLanguage("0");
            user.setCreatetime(new Date());
            user.setName(userInfo.getString("nickName"));
            user.setSex(userInfo.getInteger("gender"));

            user.setCity(userInfo.getString("city"));
            user.setProvince(userInfo.getString("province"));
            user.setCountry(userInfo.getString("country"));
            user.setHeadimgurl(userInfo.getString("avatarUrl"));
            WxUser wxUser = wxService.selectByPrimaryKey(userInfo.getString("openId"));

            if(wxUser==null){
                wxService.insertSelective(user);
            }else {


                wxService.updateUserTime(new Date(),userInfo.getString("openId"));
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("session_key", session_key);
            map.put("userInfo", user);
            return ResultDTO.getSuccess(map);
        }


        map.put("session_key", session_key);
        map.put("userInfo", user);
        return ResultDTO.getSuccess(200,"成功",map);
    }



    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @RequestMapping(value = "/info")
    public ResultDTO info(String openid) {
        WxUser wxUser =null;
        try{
            wxUser =wxService.selectByOpenid(openid);
        }catch (Exception e){
            return ResultDTO.getFailure(40001,"获取用户信息失败");
        }

        return ResultDTO.getSuccess(200,"成功",wxUser);

    }


}
